/*
 * @Author: soso
 * @Date: 2022-03-02 15:31:40
 * @LastEditTime: 2022-03-03 17:18:19
 * @LastEditors: Please set LastEditors
 * @Description: 克隆节点
 * @FilePath: /gomeshsync/cloner/cloner.go
 */

package cloner

import (
	"gomeshsync/cfile"
	"gomeshsync/consts"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"time"

	"gitee.com/kimsoso/go-utils/utils"
)

type CLfile struct {
	IsDir    bool
	Path     string
	FileSize int64
}

type Cloner struct {
	sync.RWMutex
	filesDir string
	clfiles  []*CLfile
}

var (
	clOnce   sync.Once
	clsingle *Cloner
)

func NewCloner(filesDir string) *Cloner {
	clOnce.Do(func() {
		clsingle = &Cloner{
			filesDir: filesDir,
			clfiles:  []*CLfile{},
		}
	})
	return clsingle
}

// 全部文件列表
func (cl *Cloner) allFiles() (out []*CLfile) {
	out = []*CLfile{}
	allfiles := utils.GetAllFiles(cl.filesDir)
	for _, file := range allfiles {
		if strings.HasSuffix(file, ".ctfm") {
			continue
		}

		fi, _ := os.Stat(file)
		clfile := &CLfile{
			IsDir:    fi.IsDir(),
			FileSize: fi.Size(),
		}

		clfile.Path, _ = filepath.Rel(cl.filesDir, file)

		out = append(out, clfile)
	}
	return
}

func (cl *Cloner) Commands() (out []*cfile.MCommand) {
	out = []*cfile.MCommand{}

	clfiles := cl.allFiles()

	nowUnix := time.Now().Unix()

	for ck, cl := range clfiles {
		cmd := &cfile.MCommand{
			Ck:         ck,
			Cmd:        cfile.IsADD,
			Path:       cl.Path,
			ToPath:     "",
			CreateTime: nowUnix,
			DoneTime:   0,
			Done:       false,
		}

		if !cl.IsDir {
			file := &cfile.Cfile{
				FileMd5:         "",
				FilePath:        cl.Path,
				FileSize:        cl.FileSize,
				BlockSize:       consts.BLOCKSIZE,
				FileMask:        cfile.CalFileMask(cl.FileSize, "0"),
				CreateTime:      "",
				CreateTimeStamp: nowUnix,
				Checked:         false,
			}
			cmd.File = file
		}

		out = append(out, cmd)
	}
	return
}
